<template>
  <div class="selectimg">
      <input type="file" id="filed" hidden="" @change="filePreview" enctype="multipart/form-data">
        <p @click="selectImg()"> 
            <span v-if="textHide">点击上传头像</span> 
            <img :src="src" >
        </p>
  </div>
</template>

<script>
export default {
    data() {
      return {
        src:'',
        textHide:true,
        formdata : new FormData(),
        flag:false,
        filename :''
      }
    },
    methods: {
      selectImg:function(){
        document.getElementById('filed').click()
      },
      filePreview(e){
        // let _this = this
        var files = e.target.files[0]
        if(e.target.files.length!=0){
            this.flag = true;
            this.formdata.append('img',files); 
        }
        // if (!e || !window.FileReader) return 
        // let reader = new FileReader()
        // reader.readAsDataURL(files) 
        // reader.onloadend = function () {
        //   _this.src = this.result
        //   _this.textHide=false;
        // }
        // var formdata = new FormData();    
      },
      upload(){
        return new Promise((res,rej)=>{
          if(this.flag){
                this.$http.post("http://localhost:3000/ImageUpload",this.formdata,{emulateJSON:true}).then((result)=>{
                this.src = result.body[0];
                this.filename = result.body[1];
                res(result.body[1]);
                this.formdata = new FormData();
                this.flag = false;
                
            })
          }else{
              rej("未选择图片")
          }
        })  
      }
    }
}
</script>

<style lang = 'less' scoped>
.selectimg{
  img{
    width: 100%;
  }
}
</style>   